package com.example.commons.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.commons.entity.Users;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截请求，对请求做打印
 */
@Slf4j
public class RequestFilter extends HttpServletRequestWrapper {

    @Getter
    private HttpServletRequest request;
    @Getter
    private HttpServletResponse response;
    private Map<String, String> requestHeaders;


    public Users getLoginData() {
        return (Users) request.getAttribute("login_data_bean");
    }


    public RequestFilter(HttpServletRequest request, HttpServletResponse response) {
        super(request);
        this.request = request;
        this.response = response;
    }

    public JSONObject getRequestBodyJson() {
        Map<String, String> headers = this.getHeaders();
        String ip;
        try {
            ip = this.request.getHeader("x-forwarded-for").split(",")[0];
        } catch (Exception e) {
            ip = "请求来源未知";
        }

        JSONObject bodyJson;
        String body = null;
        try {
            body = this.getBodyData();
            bodyJson = JSONObject.parseObject(body);
            if (null == bodyJson) {
                bodyJson = new JSONObject();
            }
        } catch (Exception e) {
            bodyJson = new JSONObject();
            this.getData(bodyJson, body);
        }
        Map<String, String[]> params = this.request.getParameterMap();
        for (String key : params.keySet()) {
            String val = params.get(key)[0];
            bodyJson.put(key, val);
        }
        log.info("请求来源：{}，请求方法：{}，请求参数：{}", ip, request.getMethod(), bodyJson);

        return bodyJson;
    }


    public Map<String, String> getHeaders() {
        if (requestHeaders != null) {
            return requestHeaders;
        }
        Map<String, String> heads = new HashMap<>(30);
        Enumeration<String> headerNames = this.request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = this.request.getHeader(name);
            heads.put(name, value);
        }
        requestHeaders = heads;
        return heads;
    }

    // 解析请求体中的参数
    // 这里简单示例，如果请求体是 application/x-www-form-urlencoded 格式，则可以使用类似于 URLDecoder 的方式解析参数
    // 如果请求体是 JSON 格式，则可以使用 JSON 库进行解析
    // 根据实际情况自行解析逻辑，并将参数放入 Map 中
    // 下面使用示例：x-www-form-urlencoded 格式
    public JSONObject getData(JSONObject bodyJson, String body) {
        if (StringUtils.isNotBlank(body)) {
            try {
                if (StringUtils.isNotBlank(body)) {
                    String[] str = body.split("&");
                    for (String s : str) {
                        String[] val = s.split("=");
                        try {
                            bodyJson.put(val[0], val[1]);
                        } catch (ArrayIndexOutOfBoundsException ae) {
                            bodyJson.put(val[0], "");
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
        return bodyJson;
    }

    public String getBodyData() {
        try {
            this.request.setCharacterEncoding("utf-8");
            //读取body请求体数据，转为string
            return this.readLine(this.request.getReader());
        } catch (IOException e) {
            return null;
        }
    }


    public String readLine(BufferedReader reader) throws IOException {
        // 逐行读取请求体中的数据
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}
